package com.c.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.c.menu.MenuApi;
import com.c.pojo.entity.Account;
import com.c.pojo.vo.ResultVo;
import com.c.service.AccountService;
import com.c.util.HttpUtil;
import com.c.util.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author bysun
 */
@Controller
public class MenuController {

    @Resource
    AccountService accountService;

    private static final Logger logger = LoggerFactory.getLogger(MenuController.class);

    private static final String WX_ERROR_KEY = "errcode";

    private static final Integer NO_MENU_ERROR_KRY = 46003;

    @GetMapping("/gotoMenu/{id}")
    public String gotoMenu(Model model, @PathVariable("id") Integer id) {
        String accessToken = getAccessToken(id);
        if (StringUtils.isBlank(accessToken)) {
            model.addAttribute("errorMsg", "获取accesstoken失败");
            return "redirect:/getAccounts";
        }
        String menu = MenuApi.getMenu(getAccessToken(id));
        logger.info("menu:{}", menu);
        Map<String, Object> map = JSON.parseObject(menu, Map.class);
        if (map.get(WX_ERROR_KEY) != null && Integer.valueOf(map.get(WX_ERROR_KEY).toString()) != 46003) {
            model.addAttribute("errorMsg", "获取微信菜单错误");
            return "redirect:/getAccounts";
        } else if (map.get(WX_ERROR_KEY) != null && NO_MENU_ERROR_KRY.equals(Integer.valueOf(String.valueOf(map.get(WX_ERROR_KEY))))) {
            model.addAttribute("menu", null);
        } else {
            Map<String, Object> map1 = JSON.parseObject(JSON.toJSONString(map.get("menu")), Map.class);
            model.addAttribute("menu", map1.get("button"));
        }
        model.addAttribute("accountId", id);
        return "menu";
    }

    @PostMapping("/createMenu")
    @ResponseBody
    public ResultVo createMenu(String menu, Integer id) {
        String resp = MenuApi.createMenu(getAccessToken(id), menu.trim());
        JSONObject jsonObject = JSON.parseObject(resp);
        if (jsonObject.isEmpty()
                || jsonObject.get(WX_ERROR_KEY) == null
                || Integer.valueOf(jsonObject.get(WX_ERROR_KEY).toString()) != 0) {
            return ResultUtil.error();
        }
        return ResultUtil.success();
    }

    public String getAccessToken(Integer id) {
        Account account = accountService.getAccount(id);
        String access_token = HttpUtil.get(account.getAccessTokenUrl());
        logger.info("access_token:{}", access_token);
        if (StringUtils.isBlank(access_token)) {
            return null;
        }
        logger.info("access_token:{}", access_token);
        JSONObject jo = JSON.parseObject(access_token);
        logger.info("aaaa:{}", jo.get("data").toString());
        return jo.get("data").toString();
    }
}
